package com.sxt.shiro.realm;

import com.sxt.shiro.domain.ActiverUser;
import com.sxt.shiro.domain.User;
import com.sxt.shiro.service.PermissionService;
import com.sxt.shiro.service.RoleService;
import com.sxt.shiro.service.UserService;
import com.sxt.shiro.service.imp.PermissionServiceImpl;
import com.sxt.shiro.service.imp.RoleServiceImpl;
import com.sxt.shiro.service.imp.UserServiceImpl;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.List;

public class UserRealm extends AuthorizingRealm {
    private UserService userService = new UserServiceImpl();
    private RoleService roleService=new RoleServiceImpl();
    private PermissionService permissionService =new PermissionServiceImpl();
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了----doGetAuthenticationInfo");
        String username = token.getPrincipal().toString();
        User user = userService.queryUserByUserName(username);
        /**
         * 以前登陆的逻辑是  把用户和密码全部发到数据库  去匹配
         * 在shrio里面是先根据用户名把用户对象查询出来，再来做密码匹配
         */
        if (user != null) {
            List<String> roles = roleService.queryRoleByUserName(username);
            List<String> permissions = permissionService.queryPermissionByUserName(username);
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(new ActiverUser(user, roles, permissions), user.getPwd(), this.getName());
            return info;
        } else {
            return null;
        }
    }

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        System.out.println("执行了----doGetAuthorizationInfo");
        ActiverUser activerUser = (ActiverUser) principal.getPrimaryPrincipal();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List<String> roles = activerUser.getRoles();
        List<String> permissions = activerUser.getPermissions();
        if (roles!=null&&roles.size()>0){
            info.addRoles(roles);
        }
        if (permissions!=null&&permissions.size()>0){
            info.addStringPermissions(permissions);
        }
        return info;
    }
}
